package com.xiaoye.qbdatahandle.service;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class ZipService {

    /**
     * 将多个图片打包到 ZIP 文件
     *
     * @param imagePaths  图片路径列表
     * @param zipFilePath 生成的 ZIP 文件路径
     * @throws IOException 如果文件操作失败
     */
    public void packImagesToZip(List<String> imagePaths, String zipFilePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zipOut = new ZipOutputStream(fos)) {

            for (String imagePath : imagePaths) {
                // 读取图片文件
                try (FileInputStream fis = new FileInputStream(imagePath)) {
                    // 创建 ZIP 条目
                    ZipEntry zipEntry = new ZipEntry(getFileNameFromPath(imagePath));
                    zipOut.putNextEntry(zipEntry);

                    // 将图片写入 ZIP 文件
                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = fis.read(bytes)) >= 0) {
                        zipOut.write(bytes, 0, length);
                    }
                }
            }
        }
    }

    /**
     * 从文件路径中提取文件名
     *
     * @param filePath 文件路径
     * @return 文件名
     */
    private String getFileNameFromPath(String filePath) {
        return filePath.substring(filePath.lastIndexOf("/") + 1);
    }


    /**
     * 解压 ZIP 文件并返回 Excel 文件的输入流
     *
     * @param zipFilePath ZIP 文件路径
     * @return Excel 文件的输入流
     */
    public InputStream extractExcelFromZip(String zipFilePath) throws IOException {
        File zipFile = new File(zipFilePath);
        try (ZipFile zip = new ZipFile(zipFile)) {
            Enumeration<ZipArchiveEntry> entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                if (!entry.isDirectory() && entry.getName().endsWith(".xlsx")) {
                    return zip.getInputStream(entry);
                }
            }
        }
        throw new IOException("ZIP 文件中未找到 Excel 文件");
    }
}
